<template>
	<div>
		<el-upload v-if="type==1" ref="upload"
			:action="getActionUrl"         :auto-upload="false"           list-type="picture-card" :multiple="multiple" :limit="limit"
			:headers="myHeaders" :file-list="fileList" :on-exceed="handleExceed" :on-preview="handleUploadPreview"
			:on-remove="handleRemove" :on-success="handleUploadSuccess" :on-error="handleUploadErr"
			:before-upload="handleBeforeUpload"
            :on-change="handleFileChange"    >
			<i class="el-icon-plus"></i>
			<div slot="tip" class="el-upload__tip" style="color:#838fa1;">{{tip}}</div>
		</el-upload>
		<el-upload v-else drag ref="upload"
			:action="getActionUrl"         :auto-upload="false"           :multiple="multiple" :limit="limit"
			:headers="myHeaders" :file-list="fileList" :on-exceed="handleExceed" :on-preview="handleUploadPreview"
			:on-remove="handleRemove" :on-success="handleUploadSuccess" :on-error="handleUploadErr"
			:before-upload="handleBeforeUpload"
            :on-change="handleFileChange"     >
			<i class="el-icon-upload"></i>
			  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			<div slot="tip" class="el-upload__tip" style="color:#838fa1;">{{tip}}</div>
		</el-upload>
		</div>
</template>
<script>
	import storage from "@/utils/storage";
	export default {
		data() {
			return {
				dialogVisible: false,
				dialogImageUrl: "",
				fileList: [],
				fileUrlList: [],
				myHeaders: {},
                selectedRawFile: null, // 新增：保存原始文件对象
			};
		},
		props: {
			tip: { type: String },
			action: { type: String }, // 这个 action 属性我们可以留着，但不再用于实际上传
			limit: { type: Number, default: 3 },
			multiple: { type: Boolean, default: false },
			fileUrls: { type: String },
			type: { type: Number, default: 1 }
		},
		mounted() {
			this.init();
			this.myHeaders = {
				'Token': storage.get("Token")
			}
		},
		watch: {
			fileUrls: function(val, oldVal) {
				this.init();
			}
		},
		computed: {
			// 修改 getActionUrl，使其返回一个空字符串，从而禁用 el-upload 的自动上传行为
			getActionUrl: function() {
				return ''; // 返回空字符串，防止 el-upload 发送请求
			}
		},
		methods: {
			init() {
				if (this.fileUrls) {
					this.fileUrlList = this.fileUrls.split(",");
					let fileArray = [];
					this.fileUrlList.forEach(function(item, index) {
						var url = item;
						var name = index + '_existing_file'; // 为现有文件设置一个不同的名称或标记
						var file = {
							name: name,
							url: url,
                            status: 'success' // 标记为已上传成功，防止 el-upload 显示上传中
						};
						fileArray.push(file);
					});
					this.setFileList(fileArray);
				} else {
                    this.fileList = []; // 如果没有 fileUrls，确保 fileList 是空的
                    this.fileUrlList = [];
                }
			},
            // 新增方法：处理文件选择事件，获取原始文件对象
            handleFileChange(file, fileList) {
                if (this.multiple) {
                    this.selectedRawFile = fileList.map(f => f.raw);
                    this.fileList = fileList; 
                } else {

                    if (file.status === 'ready') { 
                         this.selectedRawFile = file.raw;
 
                         this.fileList = [file];
                    } else if (file.status === 'removed') {
                         this.selectedRawFile = null;
                         this.fileList = [];
                    }
                }

                this.$emit("change", this.selectedRawFile); 
            },
            // 移除图片 (需要调整以正确更新 selectedRawFile)
            handleRemove(file, fileList) {
                // 如果 file.raw 存在，说明是新选择的文件被移除了
                if (file.raw) {
                    // 对于多文件，需要从 selectedRawFile 数组中移除
                    if (this.multiple) {
                        const index = this.selectedRawFile.findIndex(f => f === file.raw);
                        if (index > -1) {
                            this.selectedRawFile.splice(index, 1);
                        }
                    } else {
                        this.selectedRawFile = null;
                    }
                }
                // 同时更新内部 fileList 以移除预览
                this.fileList = fileList;
                // 通知父组件文件列表变化，传递更新后的原始文件或文件数组
                this.$emit("change", this.multiple ? this.selectedRawFile : null);
            },
            // 这些方法在禁用自动上传后将不再被 el-upload 自动调用，可以移除或留作备用
            handleBeforeUpload(file) {
                 return true;
            },
            handleUploadSuccess(res, file, fileList) {
 
            },
            handleUploadErr(err, file, fileList) {
				this.$message.error("文件上传失败");
            },


			handleUploadPreview(file) {
				if(this.type > 2){ 
					window.open(file.url)
					return false
				}

                if (file.raw && file.url.startsWith('blob:')) {
                    this.dialogImageUrl = file.url;
                } else { 
                    this.dialogImageUrl = file.url.split("?")[0]; 
                }
				this.dialogVisible = true;
			},
			// 限制图片数量
			handleExceed(files, fileList) {
				this.$message.warning(`最多上传${this.limit}张图片`);
			},

			setFileList(fileList) {
				var fileArray = [];
				var fileUrlArray = []; 
				var token = storage.get("token");
				let _this = this;
				fileList.forEach(function(item, index) {
   
                    let url = item.url;
 
					if (!url.startsWith("http") && !url.startsWith("blob:")) {
						url = _this.$base.url + url
					}
					var name = item.name || `file-${index}`;
					var file = {
						name: name,
						url: url + (url.includes('?') ? '&' : '?') + "token=" + token, 
                        status: item.status || 'success', 
                        raw: item.raw
					};
					fileArray.push(file);
					if (!item.raw) { 
					    fileUrlArray.push(url);
					}
				});
				this.fileList = fileArray;
				this.fileUrlList = fileUrlArray; 
			},
			     
		}
	};
</script>
<style lang="scss" scoped>
</style>